const Koa = require('koa')
const { resolve } = require('path')
// const serve = require('koa-static')
// const views = require('koa-views')
const { connect, initSchemas, initAdmin } = require('./database/init')

const R = require('ramda')
const MIDDLEWARES = ['common', 'router', 'parcel']

;
(async() => {
    await connect()
    await initSchemas()
    await initAdmin()

    // 这里是为代码配置ES6运行环境，相当于wenpack babel-loader
    //require('../start')
    //require('./task/movie') // 第一步爬取粗糙数据
    //require('./task/trailer') // 第三步爬取video、cover、poster信息
    //require('./task/api') // 第二步通过api补充缺失字段
    //require('./task/qiniu') // 第三步上传到七牛CDN

    // let Movie = mongoose.model('Movie')
    // let movies = await Movie.find()
    // console.log('movies:',movies)

    const app = new Koa()
    await useMiddlewares(app)

    //设置静态资源的路径 
    /* const staticPath = './public'

    app.use(serve(resolve(__dirname, staticPath)))

    app.use(views(resolve(__dirname, './views'), { extension: 'pug' }))

    app.use(async(ctx, next) => {
        await ctx.render('index', {
            you: 'Loading',
            me: 'Sean Ma'
        })
    }) */

    app.listen(8080, () => {
        console.log(`server running at port 8080`)
    })

})()

// 使用ramda来
    const useMiddlewares = app => {
         R.map( // 遍历每一个middleware
             R.compose( // 函数从下往上执行,先执行name
                 R.forEachObjIndexed(
                     initWith => initWith(app) // 加载进来后 初始化 app
                 ),
                 require, // 把每一个middleware加载进来
                 // 把每一个middle传递给name
                 name => resolve(__dirname, `./middlewares/${name}`)
             )
         )(MIDDLEWARES)
    }
    // //设置路由(使用decorator修饰了Route后，这里无需设置了)
    // app
    //     .use(router.routes())
    //     .use(router.allowedMethods())